package com.zhuizikejithreeig.cn.threeigkeji.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhuizikejithreeig.cn.been.AutoInfoBeen;
import com.zhuizikejithreeig.cn.been.UsrInfoBeen;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import okhttp3.Call;
/**
 * 微信登录页面
 *
 * @author kevin_chen 2016-12-10 下午19:03:45
 * @version v1.0
 */
public class WXEntryActivity extends BasicActivity implements IWXAPIEventHandler {
    private static final String APP_SECRET = "8bd46890d68d52972a3b7d2bb5d5d40f";
    private IWXAPI mWeixinAPI;
    public static final String WEIXIN_APP_ID = "wxd4b6e8d04179442b";
    private ImageView mImageHand;
    private String mOpenId;
    private Button mCerten;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.wxentryactivity);
//        getActionBar().hide();
//    // 隐藏状态栏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mWeixinAPI = WXAPIFactory.createWXAPI(this, WEIXIN_APP_ID, true);
        mWeixinAPI.handleIntent(this.getIntent(), this);
        mImageHand=(ImageView) findViewById(R.id.imagehand);
        mCerten=(Button) findViewById(R.id.certen);
        setTitle_V("微信登录");
        setLeftShow(0, R.string.string95);
        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.setString("", ContectUtils.OPENID);
                finish();
            }
        });
        mCerten.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存openid
                Utils.setString(mOpenId, ContectUtils.OPENID);
                Utils.setString("123", ContectUtils.OPENIDREGIST);
                finish();
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mWeixinAPI.handleIntent(intent, this);//必须调用此句话
    }

    //微信发送的请求将回调到onReq方法
    @Override
    public void onReq(BaseReq req) {

    }
    //发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:

                //发送成功
                SendAuth.Resp sendResp = (SendAuth.Resp) resp;
                if (sendResp != null) {
                    String code = sendResp.code;
                    getAccess_token(code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                finish();
                //发送被拒绝
                break;
            default:
                //发送返回
                finish();
                break;
        }

    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + WEIXIN_APP_ID
                + "&secret="
                + APP_SECRET
                + "&code="
                + code
                + "&grant_type=authorization_code";
        OkHttpUtils
                .get()
                .url(path)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast("授权失败,请重新授权");
                        finish();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        AutoInfoBeen been = GsonUtil.parseJsonToBean(response, AutoInfoBeen.class);
                        if (been == null) {
                            ToastMake.showToast("授权失败,请重新授权");
                            finish();
                            return;
                        } else {
                            mOpenId=been.getOpenid();
                            getUserMesg(been.getAccess_token(), been.getOpenid());
                        }
                    }
                });
    }


    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        OkHttpUtils
                .get()
                .url(path)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println("获取用户信息失败");
                        finish();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("获取用户信息成功");
                        UsrInfoBeen been = GsonUtil.parseJsonToBean(response, UsrInfoBeen.class);
                        if (been != null) {
                            Glide.with(WXEntryActivity.this).
                                    load(been.getHeadimgurl()).
                                    asBitmap().
                                    placeholder(R.mipmap.laoding).//加载中显示的图片
//                                  error(R.mipmap.eeror).//加载失败时显示的图片
                                    into(mImageHand);
                        }
                    }
                });
    }
}